package org.ktx.osr

import android.content.Intent
import android.media.projection.MediaProjectionManager
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.tooling.preview.Preview
import androidx.lifecycle.viewmodel.compose.viewModel
import org.ktx.osr.service.ScreenRecordingService
import org.ktx.osr.ui.SettingsScreen
import org.ktx.osr.ui.theme.MyApplicationTheme
import org.ktx.osr.viewmodel.SettingsViewModel

class MainActivity : ComponentActivity() {

    private var mediaProjectionManager: MediaProjectionManager? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mediaProjectionManager =
            getSystemService(MEDIA_PROJECTION_SERVICE) as MediaProjectionManager
        enableEdgeToEdge()
        setContent {
            MyApplicationTheme {
                MainScreen(
                    onNavigateBack = { finish() },
                    onStartRecording = { ScreenRecordingService.requestStartRecording(this) },
                    onStopRecording = { ScreenRecordingService.stopRecording(this) }
                )
            }
        }
    }

}

@Preview
@Composable
fun PreviewMainScreen() {
    MainScreen(
        onStartRecording = { },
        onStopRecording = {}
    )
}

@Composable
fun MainScreen(
    onNavigateBack: () -> Unit = {},
    onStartRecording: () -> Unit,
    onStopRecording: () -> Unit
) {
    val context = LocalContext.current
    val viewModel: SettingsViewModel = viewModel()
    val settings by viewModel.settings.collectAsState()

    // 监听浮动控件设置变化
    LaunchedEffect(settings.showFloatingWidget) {
        if (settings.showFloatingWidget) {
            ScreenRecordingService.requestShowFloatingWidget(context)
        } else {
            ScreenRecordingService.requestHideFloatingWidget(context)
        }
    }

    SettingsScreen(
        onNavigateBack = onNavigateBack,
        onStartRecording = onStartRecording,
        onStopRecording = onStopRecording
    )
}
